from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from BlogAutoTest.common.Utils import BlogDriver


class BlogEdit:
    def __init__(self):
        self.url="http://8.137.19.140:9090/blog_login.html"
        self.driver=BlogDriver.driver
        self.driver.get(self.url)
        self.wait=WebDriverWait(self.driver,10)
        self.expected_title="文章标题"
        self.expected_content="文章内容"
    def BlogEdit(self):
        #self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#username"))).send_keys("zhangsan")
        #self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#password"))).send_keys("123456")
        #self.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#submit"))).click()
        self.wait.until(EC.element_to_be_clickable(
            (By.CSS_SELECTOR, "body > div.nav > a:nth-child(5)"))).click()
        #检查文章标题输入框是否可以输入
        self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"#title"))).send_keys(self.expected_title)
        #检查文章内容对话框是否可以输入
        #self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"#editor > div.CodeMirror.cm-s-default.CodeMirror-wrap > div.CodeMirror-scroll"))).clear()
        #self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"#editor > div.CodeMirror.cm-s-default.CodeMirror-wrap > div.CodeMirror-scroll"))).send_keys(self.expected_content)
        # 替换原来的 clear() 和 send_keys() 操作
        editor = self.wait.until(EC.presence_of_element_located(
            (By.CSS_SELECTOR, "#editor > div.CodeMirror")
        ))

        # 清空编辑器内容
        self.driver.execute_script(
            "arguments[0].CodeMirror.setValue('');",  # 调用 CodeMirror 的 API
            editor
        )

        # 输入新内容
        self.driver.execute_script(
            f"arguments[0].CodeMirror.setValue('{self.expected_content}');",
            editor
        )
        #点击“发布文章”按钮
        self.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"#submit"))).click()
        #查看最新发布的文章标题查看是否成功发布文章
        last_title=self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"body > div.container > div.right > div:nth-child(7) > div.title"))).text
        last_content=self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"body > div.container > div.right > div:nth-child(7) > div.desc"))).text
        assert last_title == self.expected_title, f"标题不匹配，预期: {self.expected_title}，实际: {last_title}"
        assert last_content == self.expected_content, f"内容不匹配，预期: {self.expected_content}，实际: {last_content}"

        BlogDriver.getScreeShot()
